package com.example.config.auth;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.LinkedHashMap;

public class SecurityUtil {

    /**
     * 获取当前认证用户
     */
    public static Authentication getCurrentAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 获取当前认证用户的服务名
     * @return
     */
    public static String getCurrentUserServerName(){
        LinkedHashMap userAuthentication=getUserExtMap();
        if(userAuthentication!=null){
            LinkedHashMap additionalInfo= (LinkedHashMap) userAuthentication.get("additionalInfo");
            String serverName=(String) additionalInfo.get("data_node_name");
            return serverName;
        }
        return null;
    }

    public static String getCurrentUserNodeId(){
        LinkedHashMap userAuthentication=getUserExtMap();
        if(userAuthentication!=null){
            LinkedHashMap additionalInfo= (LinkedHashMap) userAuthentication.get("additionalInfo");
            String serverName=(String) additionalInfo.get("data_node_id");
            return serverName;
        }
        return null;
    }

    /**
     * 获取用户id
     * @return
     */
    public static String getUserId() {
        LinkedHashMap userAuthentication=getUserExtMap();
        if(userAuthentication!=null){
            String userId= (String) userAuthentication.get("userId");
            return userId;
        }
        return null;
    }

    /**
     * 获取用户拓展信息
     * @return
     */
    public static LinkedHashMap getUserExtMap(){
        Authentication authentication = getCurrentAuthentication();
        if(authentication!=null){
            if(authentication instanceof OAuth2Authentication){
                OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
                Authentication token=oAuth2Authentication.getUserAuthentication();
                LinkedHashMap linkedHashMap= (LinkedHashMap) token.getDetails();
                LinkedHashMap userAuthentication=(LinkedHashMap) linkedHashMap.get("userAuthentication");
                return userAuthentication;
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = getCurrentAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return null;
    }

}
